package egovframework.npqs.pqi.mobile.activity.approve;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.jsoncontent.DraftExamSerachItem;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.BodySeListItem;
import egovframework.npqs.pqi.mobile.jsonparser.DraftExamThread;
import egovframework.npqs.pqi.mobile.jsonparser.DraftExamThread.DraftExamThreadCallback;

/* 기안예문 화면*/
public class DraftExamSearchActivity extends Activity implements DraftExamThreadCallback
	, OnItemSelectedListener{
	private TextView titleTxt, navigation;
	private AppStatus myapp;
	private Context context;
	private ListView listView;
	private DraftListAdapter draftAdapter;
	private DraftExamThread draftThread;
	private ImageButton searchBtn, btnHome, btn_exit;
	private Spinner spinText;
	private String inSpinText;
	private String resutlStr;
	
	private ArrayList<BodySeListItem> draftArrList;
	private ArrayList<String> spinvalidArrList;
	
	private DraftExamSerachItem draftExamItem;
	
	private boolean firstState;
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	private String mResult;
	
	/* G-MOBILE 변수*/
    private String temp;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("기안예문");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_draft_example);
		
		resutlStr="406001";
		
		init();
	}
	
	private void init(){
		context = this;
		myapp = (AppStatus)context.getApplicationContext();
		myapp.startBroker(context);
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("기안예문");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		btn_exit = (ImageButton)findViewById(R.id.btn_exit);
		btn_exit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		listView = (ListView)findViewById(R.id.quarantine_list);
		spinText=(Spinner)findViewById(R.id.content_5_1);
		//inSpinText = spinText.getSelectedItem().toString();
		
		draftAdapter = new DraftListAdapter();
		
		searchBtn=(ImageButton)findViewById(R.id.search_btn);
		searchBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//myapp.utilm.InputKeybordHidden(context, offEdit);
				searchDraftResult();
			}
		});
		
		//resutlStr="";
		firstState = false;
		dateLoad();
		
	}
	
	private void searchDraftResult(){
		dateLoad();
		/*if(offEdit.getText().toString().equals("")){
			myapp.utilm.ShowDialog(DraftExamSearchActivity.this, "실패", "ID 또는 이름을 입력하세요.", 20);
		}else{
			dateLoad();
		}*/
	}
	
	private void dateLoad(){
		myapp.showDialogNo(context);	// 페이지가 로드 될때 다이얼로그 출력.
		temp = "조건검색";
		threadStart();
	}
	
	public void threadStart(){
		if("조건검색".equals(temp)){
    		draftThread = new DraftExamThread(context, this, resutlStr, AppStatus.getmUserId());
    		draftThread.start();
    	}
	}
	
	private void layoutSetting() {
		draftArrList = myapp.getArrDraftExamItem().get(0).getBodySeList();
		Log.i("draftArrList","draftArrList =" + draftArrList.size());
		
		if(draftArrList.size() > 0){
			spinvalidArrList = new ArrayList<String>();
			for (int i = 0; i < draftArrList.size(); i++) {
				spinvalidArrList.add(draftArrList.get(i).getCodeNm());
			}
		}
		
		ArrayAdapter<String> validAdapter 
		= new ArrayAdapter<String>(context,  R.layout.spinner_item, spinvalidArrList);
		validAdapter.setDropDownViewResource(R.layout.spinner_item);
		spinText.setAdapter(validAdapter);
		
		for (int i = 0; i < draftArrList.size(); i++) {
			if(draftArrList.get(i).getCode().equals(resutlStr)){
				spinText.setSelection(i);
			}
		}
		spinText.setOnItemSelectedListener(this);		
		listView.setAdapter(draftAdapter);
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				layoutSetting();
				firstState = true;
				/*officerAdapter.notifyDataSetChanged();
				listView.setAdapter(officerAdapter);*/
				
				/*if(myapp.getArrDraftExamItem().size() == 1){
					returnToActivity();
				}else{
					draftAdapter.notifyDataSetChanged();
					listView.setAdapter(draftAdapter);	
				}*/
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				
				draftAdapter.notifyDataSetChanged();
				listView.setAdapter(draftAdapter);
				
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(context, "실패", "네트워크에러", 20);

			default:
				break;
			}
		}
	};
	
	private void returnToActivity(){
		Intent intent = new Intent();
		intent.putExtra("dragBody", myapp.getArrDraftExamItem().get(0).getDrafBody());
		intent.putExtra("drafCd", myapp.getArrDraftExamItem().get(0).getDrafCd());
		intent.putExtra("jobSe", myapp.getArrDraftExamItem().get(0).getJobSe());
		intent.putExtra("bodySeList", myapp.getArrDraftExamItem().get(0).getBodySeList());
		setResult(1, intent);
		finish();
	}
	
	class DraftListAdapter extends BaseAdapter {
		TextView draftBody;

		@Override
		public int getCount() {
			return myapp.getArrDraftExamItem().size();
		}

		@Override
		public Object getItem(int position) {
			return myapp.getArrDraftExamItem().get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_draft_example_item, parent, false);
    		}
			
			draftBody = (TextView)convertView.findViewById(R.id.draft_body);
			draftBody.setText(myapp.getArrDraftExamItem().get(position).getDrafBody());
			
			convertView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {
			Intent intent = new Intent();
			intent.putExtra("draftBody", myapp.getArrDraftExamItem().get(position).getDrafBody());
			intent.putExtra("drafCd", myapp.getArrDraftExamItem().get(position).getDrafCd());
			setResult(1, intent);
			finish();
		}
	}
	
	@Override
	public void OnDraftExamCompleted(boolean isNetworkConntected,
			boolean results, String message) {
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(results) {
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
	}

	@Override
	public void OnDraftExamError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		switch (parent.getId()) {
		case R.id.content_5_1:
			if(firstState){
				myapp.getArrDraftExamItem().get(0).setDrafCd(draftArrList.get(position).getCodeNm());
				resutlStr = draftArrList.get(position).getCode();	
			}
			
			break;

		default:
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}
	
	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
	
}
